import { http } from "@/utils/http";
import { baseUrlApi } from "./utils";
import axios from 'axios';

type ResponseFile = {
  full_path: string;
  path: string;
};

type Result = {
  code: boolean;
  data: ResponseFile;
  msg: string;
};

export const uploadBase64 = (data?: object) => {
  return http.request<Result>("post", baseUrlApi("/common/uploadBase64"), {
    data
  });
};

export const uploadFiles = (data?: object) => {
  return http.request<Result>(
    "post",
    baseUrlApi("/common/uploadFiles"),
    {
      data
    },
    {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    }
  );
};


 export async function handleExport(url:string, data?: object) {

   try {
      // 发送POST请求
      const response = await axios.post(
        url,  // API 地址
        data,
        {
          // 配置 headers
          headers: {
            'accept': 'application/json',
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTgwMDAwNDIzNH0.ClUATbEHRRAfOvxQDxkMuyBoZNxGmF5__M0IxteK_xk',
            'Content-Type': 'application/json'
          },
          // 设置为允许携带 cookie 等凭证，如果需要跨域设置
          withCredentials: true,
          // 如果响应是文件（如 CSV），则使用 'blob' 作为响应类型
          responseType: 'blob'
        }
      );
        // 处理返回的文件内容
        const blob = new Blob([response.data], { type: 'text/csv' });
        const contentDisposition = response.headers['content-disposition'];
        let filename = 'download.csv'; // 默认文件名

        // 尝试从 content-disposition 获取文件名
        if (contentDisposition && contentDisposition.includes('filename=')) {
          filename = contentDisposition.split('filename=')[1].trim();
        }

        // 创建下载链接并触发下载
        const downurl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downurl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        a.remove(); // 下载完成后移除链接
        // 释放 URL 对象
        window.URL.revokeObjectURL(downurl);
      
    } catch (error) {
      console.error('Error downloading the file:', error);
    }
  }
